package org.puppet.demo.mario;

import org.puppet.game.base.PuppetUtils;
import org.puppet.game.control.AbstractController;
import org.puppet.game.control.TouchController;

public class MarioController extends AbstractController {

	private TouchController touchHandler;

	private boolean ctrlPlayer = false;
	private Mario mario;
	private float defaultAccY = -0.0028f;

	private float speedFix = 650f;

	public MarioController(Mario mario) {
		this.mario = mario;
	}

	public boolean action(Integer eventId, Object e) {
		touchHandler = (TouchController) e;
		if (eventId.equals(TouchController.EVENT_DOWN)) {
			onTouchDown();
		} else if (eventId.equals(TouchController.EVENT_UP)) {
			onTouchUp();
		}
		return true;
	}

	public boolean onTouchDown() {
		ctrlPlayer = PuppetUtils.pointInRect(touchHandler.getFirstPoint(), mario.getLeft(), mario.getTop(), mario.getWidth(), mario.getHeight());
		if (!ctrlPlayer && !mario.isJumping()) {
			float xv = 0.4f;
			if (touchHandler.getX() < mario.x) {
				xv = 0 - xv;
			}
			mario.walk(xv, 0);
		}
		return true;
	}

	public boolean onTouchUp() {
		if (ctrlPlayer && !mario.isJumping()) {
			mario.acceY = defaultAccY;
			mario.jump((float) (touchHandler.getVelocityX() / speedFix), (float) (touchHandler.getVelocityY() / speedFix));
			ctrlPlayer = false;
		}
		if (!ctrlPlayer && mario.isWalking()) {
			mario.stand();
		}

		return true;
	}

	public int[] lookEvent() {
		return new int[]{TouchController.EVENT_DOWN, TouchController.EVENT_UP};
	}

}
